package com.doeis.uwork.servce;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.doeis.common.utils.BeanUtils;
import com.doeis.common.utils.StringUtils;
import com.doeis.minaserver.NettyServer;
import com.doeis.minaserver.container.BasicModule;
import com.doeis.minaserver.dao.User;
import com.doeis.minaserver.dao.UserDao;
import com.doeis.minaserver.module.ClientConnectionManager;
import com.doeis.minaserver.packet.InfoPacket;
import com.doeis.minaserver.packet.ServerPacketFactory;
import com.doeis.minaserver.session.ClientConnection;
import com.doeis.uwork.bean.MessageIn;
import com.doeis.uwork.bean.ReplyIn;
import com.doeis.uwork.common.Constant;
import com.doeis.uwork.dao.HnMsgAuthorityDao;
import com.doeis.uwork.dao.HnMsgAuthorityPeopleDao;
import com.doeis.uwork.dao.MessageDao;
import com.doeis.uwork.entity.HnMsgAuthority;
import com.doeis.uwork.entity.HnMsgAuthorityPeople;
import com.doeis.uwork.entity.mongo.Message;
import com.doeis.uwork.entity.mongo.MessageUser;
import com.doeis.uwork.entity.mongo.Reply;
import com.doeis.uwork.packet.MessagePacket;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.voland.core.ServiceException;
import com.voland.core.db.DBManager;
import com.voland.core.utils.DateUtils;
import com.voland.core.utils.IDGenerator;

public class MessageService extends BasicModule {

	private static final Logger log = Logger.getLogger(MessageService.class);
	
	private UserDao userDao;
	private MessageDao messageDao;
	private HnMsgAuthorityDao authorityDao;
	private HnMsgAuthorityPeopleDao authorityPeopleDao;
	private ClientConnectionManager clientConnectionManager = null ;
	
	
	public MessageService() {
		super(" Message Service ");
	}
	
	public MessageService(String moduleName) {
		super(moduleName);
	}

	@Override
	public void initialize(NettyServer server) {
		this.server = server;
		
		clientConnectionManager = server.getClientConnectionManager();
		userDao = server.getUserDao();
		messageDao = server.getMessageDao();
		authorityDao = server.getHnMsgAuthorityDao();
		authorityPeopleDao = server.getHnMsgAuthorityPeopleDao();
		
	}
	
	/**
	 * 添加信息
	 * @param clientConn
	 * @param packet
	 */
	public void addMsg(ClientConnection clientConn, MessagePacket packet) {
		MessageIn messageIn = packet.decoder(MessageIn.class);
		try{
			//验证登陆输入的参数
			Map<String, Object> errerInfos = new HashMap<String, Object>();
			if (BeanUtils.validate(messageIn,errerInfos)) {				
				sendSystemPacket(clientConn, packet.getFrom(),errerInfos.toString(),MessagePacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			User user = userDao.findUserByid(messageIn.getUser_id());
			if(user==null){
				sendSystemPacket(clientConn, packet.getFrom(),"没有找到用户",MessagePacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			
			String[] to_user_ids = null;
			if(StringUtils.isBlank(messageIn.getTo_user_ids())){
				List<User> listUsers = userDao.findUserBySwitchBoard(user.getSwitchboard_id(), false);
				if(listUsers!=null){
					to_user_ids = new String[listUsers.size()];
					for(int i=0;i<listUsers.size();i++){
						to_user_ids[i] =listUsers.get(i).getId(); 
					}
				}else{
					to_user_ids = new String[0];
				}
			}else{
				to_user_ids = messageIn.getTo_user_ids().split(",");
			}
			
			
			String[] cc_user_id_array = null;
			String cc_user_ids = messageIn.getCc_user_ids();
			if(!StringUtils.isBlank(cc_user_ids)){
				cc_user_id_array = cc_user_ids.split(",");
			}
			if(messageIn.getScene_time()==null){
				messageIn.setScene_time(DateUtils.currentDateTime());
			}
			
			Message message = new Message();
			message.set_countdown(messageIn.getCountdown());
			message.set_user_id(messageIn.getUser_id());
			message.set_scene_id(messageIn.getScene_id());
			message.set_scene_type(messageIn.getScene_type());
			message.set_content(messageIn.getContent());
			message.set_img(messageIn.getImg());
			message.set_scene_time(messageIn.getScene_time().getTime());
			MessageUser _from = new MessageUser();
			_from.setUser_id(messageIn.getUser_id());
			_from.setName(user.getName());
			message.set_form(_from);
			
			message = add(message, to_user_ids, cc_user_id_array, user.getSwitchboard_id(),packet,clientConn);
			packet.setTo(messageIn.getUser_id());
			packet.setBody(JSON.toJSONString(message));
			
			MessagePacket reply = ServerPacketFactory.replyAddMessage(packet);
			reply.setNotifyType(MessagePacket.NT_RE_MSG_OK);
			clientConn.deliver(reply);
		}catch(Exception e){
			e.printStackTrace();
			log.error("查询用户", e.getCause());
		}finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
	}
	
	private Message add(Message message, String[] to_user_ids, 
			String[] cc_user_ids, String switchboard, MessagePacket packet, ClientConnection clientConn) throws ServiceException{
		try{
			MessagePacket p = (MessagePacket)packet.clone();
			Set<String> idsSet = new HashSet<String>();
			String creator = message.get_user_id();//信息创建者
			cc_user_ids = StringUtils.hashSetToString(cc_user_ids,to_user_ids);
			List<MessageUser> toUsers = new ArrayList<MessageUser>();
			List<MessageUser> ccUsers = new ArrayList<MessageUser>();
			Map<String, MessageUser> toUsersMap = new HashMap<String, MessageUser>();
			User user = null;
			MessageUser messageUser = null;
			Map<String, String> user_switchboard = new HashMap<String, String>();
			//设置发送给谁
			for(String to : to_user_ids){
				if (to.equals(creator)) {
					continue;
				}
				user = userDao.findUserByid(to);
				if(user!=null ){
					messageUser = new MessageUser();
					messageUser.setName(user.getName());
					messageUser.setUser_id(user.getId());
					user_switchboard.put(user.getId(), user.getSwitchboard_id());
					toUsers.add(messageUser);
					toUsersMap.put(user.getId(), messageUser);
				}
			}			
			message.set_tos(toUsers);
			
			if(cc_user_ids!=null){
				//设置抄送给谁
				for(String cc : cc_user_ids){
					if (cc.equals(creator)) {
						continue;
					}
					user = userDao.findUserByid(cc);
					if(user!=null ){
						//过滤掉发送了给他，又抄送给他的情况
						if(toUsersMap.get(cc)!=null)
							continue;
						messageUser = new MessageUser();
						user_switchboard.put(user.getId(), user.getSwitchboard_id());
						messageUser.setName(user.getName());
						messageUser.setUser_id(user.getId());
						ccUsers.add(messageUser);
					}
				}
			}
			message.set_ccs(ccUsers);
			
			//自己的message
			String topicId = IDGenerator.shotid();
			message.set_id(IDGenerator.uuid());
			message.set_topic_id(topicId);
			long time = DateUtils.currentTime();
			message.set_created_at(time);
			message.set_reply_at(time);
			messageDao.insert(switchboard, Message.class, message);
			//发送给自己的上级
			sendToParent(switchboard, creator, message,idsSet,packet,clientConn);
			//所有抄送与发送人的message
			Message tmp = null;
			String to_user_id = null;
			DBObject query = new BasicDBObject();
			query.put("_topic_id", topicId);
			DBObject hasExist = null;
			
			for(MessageUser to: toUsers){
				to_user_id = to.getUser_id();
				tmp = (Message)message.clone();
				tmp.set_id(IDGenerator.uuid());
				tmp.set_user_id(to_user_id);
				query.put("_user_id", to_user_id);
				hasExist = messageDao.readByCondition(user_switchboard.get(to_user_id), Message.class, query);
				if (hasExist==null) {
					messageDao.insert(user_switchboard.get(to_user_id), Message.class, tmp);
					if (!idsSet.contains(to_user_id)) {
						//推送给其他人
						p.setTo(to_user_id);
						p.setBody(JSON.toJSONString(tmp));
						MessagePacket reply = ServerPacketFactory.replyAddOtherMessage(p);
						reply.setNotifyType(MessagePacket.NT_RE_MSG_OK);
						ClientConnection clientConnection = clientConnectionManager.getAuthConnection(to_user_id);
						if(clientConnection!=null){
							clientConnection.deliver(reply);
						}
						idsSet.add(to_user_id);
					}
					//发送给接收者的上级
					sendToParent(user_switchboard.get(to_user_id), to_user_id, message,idsSet,packet,clientConn);
				}
			}
			for(MessageUser cc: ccUsers){
				to_user_id = cc.getUser_id();
				tmp = (Message)message.clone();
				tmp.set_id(IDGenerator.uuid());
				tmp.set_user_id(to_user_id);
				query.put("_user_id", to_user_id);
				hasExist = messageDao.readByCondition(user_switchboard.get(to_user_id), Message.class, query);
				if (hasExist==null) {
					messageDao.insert(user_switchboard.get(to_user_id), Message.class, tmp);
					if (!idsSet.contains(to_user_id)) {
						//推送给其他用户
						p.setTo(to_user_id);
						p.setBody(JSON.toJSONString(tmp));
						MessagePacket reply = ServerPacketFactory.replyAddOtherMessage(p);
						ClientConnection clientConnection = clientConnectionManager.getAuthConnection(to_user_id);
						if(clientConnection!=null){
							reply.setNotifyType(MessagePacket.NT_RE_MSG_OK);
							clientConnection.deliver(reply);
							idsSet.add(to_user_id);
						}
					}
					//发送给抄送者的上级
					sendToParent(user_switchboard.get(to_user_id), to_user_id, message,idsSet,packet,clientConn);
				}
			}
			
			return message;
		}catch(Exception e){
			throw new ServiceException(e);
		}		
	}
	/**
	 * 发送聊天信息到上一级
	 * @param switchboard
	 * @param user_id
	 * @param message
	 * @throws Exception
	 * @author wxy
	 * 2014年10月22日星期三中国标准时间下午1:00:10
	 * @param idsSet 
	 * @param clientConn 
	 * @param packet 
	 */
	public void sendToParent(String switchboard,String user_id,Message message, Set<String> idsSet, MessagePacket packet, ClientConnection clientConn) throws Exception{
		MessagePacket p = (MessagePacket)packet.clone();
		String topicId = message.get_topic_id();
		//查询是否在权限查看关系表内
		HnMsgAuthority hnMsgAuthorityForm = new HnMsgAuthority();
		hnMsgAuthorityForm.setSwitchboard_id(switchboard);
		hnMsgAuthorityForm.setStatus(true);
		hnMsgAuthorityForm.setMsg_user_id(user_id);
		List<HnMsgAuthority> authoritys = authorityDao.listHnMsgAuthoritys(hnMsgAuthorityForm);
		String user_id2 = switchboard;
		if (authoritys!=null&&authoritys.size()>0) {
			HnMsgAuthority hnMsgAuthority = authoritys.get(0);
			String level = hnMsgAuthority.getLevel();
			if (level!=null&&level.length()!=4) {
				HnMsgAuthority parentAuthority = authorityDao.findHnMsgAuthorityByid(hnMsgAuthority.getParent_id());
				user_id2 = parentAuthority.getMsg_user_id();
			}
			DBObject query = new BasicDBObject();
			query.put("_topic_id", topicId);
			DBObject hasExist = null;
			query.put("_user_id", user_id2);
			hasExist = messageDao.readByCondition(switchboard, Message.class, query);
			if (hasExist==null) {
				Message tmp = (Message)message.clone();
				tmp.set_id(IDGenerator.uuid());
				tmp.set_user_id(user_id2);
				messageDao.insert(switchboard, Message.class, tmp);
				//是否需要推送信息
				List<HnMsgAuthorityPeople> list = authorityPeopleDao.findHnMsgAuthorityListByAuthorityId(hnMsgAuthority.getParent_id());
				if (list!=null&&list.size()>0) {
					for (HnMsgAuthorityPeople hnMsgAuthorityPeople : list) {
						if (!idsSet.contains(hnMsgAuthorityPeople.getUser_id())) {
							//BaiduPush.sendMessage(switchboard,hnMsgAuthorityPeople.getUser_id(), tmp);
							p.setTo(hnMsgAuthorityPeople.getUser_id());
							p.setBody(JSON.toJSONString(tmp));
							MessagePacket reply = ServerPacketFactory.replyAddOtherMessage(p);
							reply.setNotifyType(MessagePacket.NT_RE_MSG_OK);
							ClientConnection clientConnection = clientConnectionManager.getAuthConnection(hnMsgAuthorityPeople.getUser_id());
							if(clientConnection!=null){
								clientConnection.deliver(reply);
							}
							idsSet.add(hnMsgAuthorityPeople.getUser_id());
						}
					}
				}
			}
		}
		
		//查看是否在查看人员关系表内
		HnMsgAuthorityPeople hnMsgAuthorityPeople = new HnMsgAuthorityPeople();
		hnMsgAuthorityPeople.setUser_id(user_id);
		hnMsgAuthorityPeople.setSwitchboard_id(switchboard);
		HnMsgAuthorityPeople people = authorityPeopleDao.findHnMsgAuthorityPeopleByForm(hnMsgAuthorityPeople);
		if (people!=null) {
			HnMsgAuthority parentAuthority = authorityDao.findHnMsgAuthorityByid(people.getHn_msg_authority_id());
			user_id2 = parentAuthority.getMsg_user_id();
			
			DBObject query = new BasicDBObject();
			query.put("_topic_id", topicId);
			DBObject hasExist = null;
			query.put("_user_id", user_id2);
			hasExist = messageDao.readByCondition(switchboard, Message.class, query);
			if (hasExist==null) {
				Message tmp = (Message)message.clone();
				tmp.set_id(IDGenerator.uuid());
				tmp.set_user_id(user_id2);
				messageDao.insert(switchboard, Message.class, tmp);
				//是否需要推送信息
				List<HnMsgAuthorityPeople> list = authorityPeopleDao.findHnMsgAuthorityListByAuthorityId(people.getHn_msg_authority_id());
				if (list!=null&&list.size()>0) {
					for (HnMsgAuthorityPeople authorityPeople : list) {
						if (!idsSet.contains(authorityPeople.getUser_id())) {
							p.setTo(authorityPeople.getUser_id());
							p.setBody(JSON.toJSONString(tmp));
							MessagePacket reply = ServerPacketFactory.replyAddOtherMessage(p);
							reply.setNotifyType(MessagePacket.NT_RE_MSG_OK);
							ClientConnection clientConnection = clientConnectionManager.getAuthConnection(authorityPeople.getUser_id());
							if(clientConnection!=null){
								clientConnection.deliver(reply);
							}
							idsSet.add(authorityPeople.getUser_id());
						}
					}
				}
			}
		}
	}
	
	/**
	 * 获取列表聊天信息
	 * @param userId 用户ID
	 * @param _start 开始个数
	 * @param _end 结束个数
	 * @param clientConn
	 * @param p
	 */
	public void listMsg(ClientConnection clientConn, MessagePacket p) {
		MessageIn messageIn = p.decoder(MessageIn.class);
		
		//验证登陆输入的参数
		String user_id = messageIn.getUser_id();
		try{
			if (StringUtils.isBlank(user_id)) {
				sendSystemPacket(clientConn, p.getFrom(),"用户user_id不能为空",MessagePacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			User user = userDao.findUserByid(user_id);
			if(user==null){
				sendSystemPacket(clientConn, p.getFrom(),"没有找到用户",MessagePacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			
			Integer start = 0;
			String _start = messageIn.getStart();
			if(!StringUtils.isBlank(_start)){
				start = Integer.parseInt(_start);
			}
			Integer end = start+10;
			String _end = messageIn.getCount();
			if(!StringUtils.isBlank(_end)){
				end = Integer.parseInt(_end);
			}
			//是否有查看权限
			HnMsgAuthorityPeople form = new HnMsgAuthorityPeople(); 
			form.setUser_id(user_id);
			form.setSwitchboard_id(user.getSwitchboard_id());
			HnMsgAuthorityPeople authorityPeople = authorityPeopleDao.findHnMsgAuthorityPeopleByForm(form);
			if(authorityPeople!=null){
				HnMsgAuthority authority = authorityDao.findHnMsgAuthorityByid(authorityPeople.getHn_msg_authority_id());
				if(authority!=null){
					user_id = authority.getMsg_user_id();
				}
			}
			String dbname = user.getSwitchboard_id();
			BasicDBObject query = new BasicDBObject();
			query.put("_user_id", user_id);
			BasicDBObject sort = new BasicDBObject();
			sort.put("_reply_at", -1);
			
			List<DBObject> listDBObject = messageDao.querySlice(dbname, Message.class, start,end, query, sort);
			p.setTo(messageIn.getUser_id());
			p.setBody(JSON.toJSONString(listDBObject));
			MessagePacket reply = ServerPacketFactory.replyListMessage(p);
			reply.setNotifyType(MessagePacket.NT_RE_MSG_OK);
			clientConn.deliver(reply);
		}catch(Exception e){
			log.error("获取聊天列表信息出错", e);
			sendSystemPacket(clientConn, p.getFrom(),e.getMessage(),MessagePacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PRO_ERROR);
		} finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
	}
	/**
	 * 回复聊天信息
	 * @param messageid
	 * @param replyto
	 * @param replyType
	 * @param content
	 * @param img  回复的图片
	 * @param userId 登陆者
	 * **/
	public void replyMsg(ClientConnection clientConn, MessagePacket p) {
		ReplyIn replyIn = p.decoder(ReplyIn.class);	
		String user_id = replyIn.getUserId();
		try{
			if (StringUtils.isBlank(user_id)) {
				sendSystemPacket(clientConn, p.getFrom(),"用户user_id不能为空",MessagePacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			User user = userDao.findUserByid(user_id);
			if(user==null){
				sendSystemPacket(clientConn, p.getFrom(),"没有找到用户",MessagePacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PARAM_NULL);
				return ;
			}
			if(replyIn.getScene_time()==null){
				replyIn.setScene_time(DateUtils.currentDateTime());
			}
			
			Reply reply = new Reply();
			reply.setUser_id(replyIn.getUserId());
			reply.setName(user.getName());
			reply.setContent(replyIn.getContent());
			reply.setImg(replyIn.getImg());
			reply.setScene_time(replyIn.getScene_time().getTime());
			
			boolean replyOk = reply(reply, replyIn.getReplyto(), replyIn.getMessageid(),replyIn.getReplyType(), user.getSwitchboard_id(),replyIn.getUserId(),p);
			
			p.setTo(user_id);
			if(replyOk){
			//通知自己，理论上还要通知别人
				//msg.setUrl(replyIn.getMessageid());
				if(Constant.REPLY_TYPE_ALL.equals(replyIn.getReplyType())){
					reply.setTo_name(user.getName());
				}else{
					User user2 = userDao.findUserByid(replyIn.getReplyto());
					if(user2!=null){
						reply.setTo_name(user2.getName());
					}else {
						reply.setTo_name("用户不存在");
					}
				}
				p.setBody(JSON.toJSONString(reply));
				MessagePacket replyPacket = ServerPacketFactory.replyMessage(p);
				replyPacket.setNotifyType(MessagePacket.NT_RE_MSG_OK);
				clientConn.deliver(replyPacket);
			}else{
				sendSystemPacket(clientConn, p.getFrom(),"回复失败",MessagePacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PRO_ERROR);
			}
		}catch(Exception e){
			log.error("增加聊天信息出错", e);
			sendSystemPacket(clientConn, p.getFrom(),e.getMessage(),MessagePacket.NT_RE_MSG_OK,InfoPacket.NOTIFY_PRO_ERROR);
		} finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
	}
	
	public boolean reply(Reply reply, String replyto, String messageid, String replyType,
			String switchboard,String faqizhe, MessagePacket p) throws ServiceException{
		try{
			User replyToUser = null;
			Set<String> idsSet = new HashSet<String>();
			//先查出自己的那条主题信息
			DBObject myMessage = messageDao.readById(switchboard, Message.class, messageid);
			if(myMessage == null)
				return false;
			
			String _my_user_id = myMessage.get("_user_id").toString();
//			BasicDBObject fromUser = (BasicDBObject) myMessage.get("_form");
			
			String _topic_id = myMessage.get("_topic_id").toString();
			BasicDBObject querySelf = new BasicDBObject();
			querySelf.put("_topic_id", _topic_id);
			List<DBObject> allMessage = messageDao.query(switchboard, Message.class, querySelf, null);
			

			if (_my_user_id.equals(switchboard)&&Constant.REPLY_TYPE_TOPIC.equals(replyType)) {
				_my_user_id = faqizhe;
			}
			String _user_id = null;
			for(DBObject message: allMessage){
				_user_id = message.get("_user_id").toString();
				
				if(Constant.REPLY_TYPE_ALL.equals(replyType)){
					replyToUser = userDao.findUserByid(_user_id);
					if(replyToUser==null){
						if (!_user_id.equals(switchboard)) {
							continue;
						}
					}else {
						//reply.setTo_name(replyToUser.getName());
					}
					reply.setTo_user_id(_user_id);
					reply.setTo_name("全部");
					//更新到所有人
					addReplyToMessage(message, reply,replyToUser==null?switchboard:replyToUser.getSwitchboard_id(),faqizhe,replyType,idsSet,p);
				}else if(Constant.REPLY_TYPE_TOPIC.equals(replyType) && 
						(_my_user_id.equals( _user_id ) ||_user_id.equals( replyto )||_user_id.equals(switchboard))){
					//更新到自己与对方
					replyToUser = userDao.findUserByid(replyto);
					if(replyToUser==null){
						if (!_user_id.equals(switchboard)) {
							continue;
						}
					}else {
						//reply.setTo_name(replyToUser.getName());
					}
					reply.setTo_user_id(replyto);
					reply.setTo_name(replyToUser.getName());
					addReplyToMessage(message, reply,replyToUser==null?switchboard:replyToUser.getSwitchboard_id(),faqizhe,replyType,idsSet,p);
				}		
				System.err.println("idsSet==="+idsSet.hashCode());
			}
			
			return true;
		}catch(Exception e){
			e.printStackTrace();
			throw new ServiceException(e);
		} finally{
			DBManager.closeBindConnection(DBManager.getDefaultDataSourceName(Boolean.TRUE.booleanValue()));
		}
	}
	
	public void addReplyToMessage(DBObject message, Reply reply, String switchboard
			,String faqizhe,String replyType, Set<String> idsSet, MessagePacket p) throws Exception{
		MessagePacket packet = (MessagePacket)p.clone();
		List<BasicDBObject> replyList = (List<BasicDBObject>)message.get("_replys");
		if(replyList==null){
			replyList = new ArrayList<BasicDBObject>();
		}
		
		reply.set_id(IDGenerator.shotid());
		reply.setReply_at(DateUtils.currentTime());
		
		BasicDBObject basicDBObject = new BasicDBObject();
		basicDBObject.append("Content", reply.getContent());
		basicDBObject.append("Img", reply.getImg());
		basicDBObject.append("Name", reply.getName());
		basicDBObject.append("Reply_at", reply.getReply_at());
		basicDBObject.append("Scene_time", reply.getScene_time());
		basicDBObject.append("To_name", reply.getTo_name());
		basicDBObject.append("To_user_id", reply.getTo_user_id());
		basicDBObject.append("User_id", reply.getUser_id());
		basicDBObject.append("_id", reply.get_id());
		replyList.add(basicDBObject);
		message.put("_replys", replyList);
		message.put("_reply_at", DateUtils.currentTime());
		messageDao.update(switchboard, Message.class, message);
		
		String _user_id = message.get("_user_id").toString();
		if (_user_id.equals(switchboard)) {
			if(Constant.REPLY_TYPE_ALL.equals(replyType)){
				HnMsgAuthority hnMsgAuthorityForm = new HnMsgAuthority();
				hnMsgAuthorityForm.setSwitchboard_id(switchboard);
				hnMsgAuthorityForm.setStatus(true);
				hnMsgAuthorityForm.setMsg_user_id(_user_id);
				List<HnMsgAuthority> authoritys = authorityDao.listHnMsgAuthoritys(hnMsgAuthorityForm);
				if (authoritys!=null&&authoritys.size()>0) {
					HnMsgAuthority hnMsgAuthority = authoritys.get(0);
					//是否需要推送信息
					List<HnMsgAuthorityPeople> list = authorityPeopleDao.findHnMsgAuthorityListByAuthorityId(hnMsgAuthority.getParent_id());
					if (list!=null&&list.size()>0) {
						for (HnMsgAuthorityPeople hnMsgAuthorityPeople : list) {
							if(!faqizhe.equals(hnMsgAuthorityPeople.getUser_id())){
								if (!idsSet.contains(hnMsgAuthorityPeople.getUser_id())) {
									idsSet.add(hnMsgAuthorityPeople.getUser_id());
									packet.setTo(hnMsgAuthorityPeople.getUser_id());
									packet.setBody(JSON.toJSONString(message));
									MessagePacket replyPacket = ServerPacketFactory.replyOutMessage(packet);
									replyPacket.setNotifyType(MessagePacket.NT_RE_MSG_OK);
									ClientConnection clientConnection = clientConnectionManager.getAuthConnection(hnMsgAuthorityPeople.getUser_id());
									if(clientConnection!=null){
										clientConnection.deliver(replyPacket);
									}
								}
							}
						}
					}
				}
			}else if(Constant.REPLY_TYPE_TOPIC.equals(replyType)){
				String to_user_id = reply.getTo_user_id();
				if (!StringUtils.isBlank(to_user_id)) {
					if (!idsSet.contains(to_user_id)) {
						idsSet.add(to_user_id);
						packet.setTo(to_user_id);
						packet.setBody(JSON.toJSONString(message));
						MessagePacket replyPacket = ServerPacketFactory.replyOutMessage(packet);
						replyPacket.setNotifyType(MessagePacket.NT_RE_MSG_OK);
						ClientConnection clientConnection = clientConnectionManager.getAuthConnection(to_user_id);
						if(clientConnection!=null){
							clientConnection.deliver(replyPacket);
						}
					}
				}
			}
		}else {
			HnMsgAuthorityPeople hnMsgAuthorityPeople = new HnMsgAuthorityPeople();
			hnMsgAuthorityPeople.setUser_id(_user_id);
			hnMsgAuthorityPeople.setSwitchboard_id(switchboard);
			HnMsgAuthorityPeople people = authorityPeopleDao.findHnMsgAuthorityPeopleByForm(hnMsgAuthorityPeople);
			if (people==null) {
				if(!faqizhe.equals(_user_id)){
					if (!idsSet.contains(_user_id)) {
						idsSet.add(_user_id);
						//BaiduPush.sendMessage(switchboard,_user_id, message);
						packet.setTo(_user_id);
						packet.setBody(JSON.toJSONString(message));
						MessagePacket replyPacket = ServerPacketFactory.replyOutMessage(packet);
						replyPacket.setNotifyType(MessagePacket.NT_RE_MSG_OK);
						ClientConnection clientConnection = clientConnectionManager.getAuthConnection(_user_id);
						if(clientConnection!=null){
							clientConnection.deliver(replyPacket);
						}
					}
				}
			}
		}
	}

}
